import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import autobind from "autobind-decorator";
import { WhiteSpace, Button } from "@ali/ding-ui";
import { setTitle, toast } from "../../../utils/dingtalk.js";
import { setCacheData, getCacheData } from "../../../utils/storeCache.js";
import { fetchServiceCenterInfo, inviteOpenHrmCenter } from "../../../actions/hrCenter/";
import Icon from "../../../components/Icon/index.jsx";
import { get } from "../../../utils/db.js";

const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(
    {
      dispatch,
      fetchServiceCenterInfo,
      inviteOpenHrmCenter
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class ServiceCenter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hrCenterInfo: "",
      showNotification: false
    };
    setTitle({
      title: "智能人事"
    });
  }
  
  componentDidMount() {
    const t = this;
    // window.dd.ready(function () {
    //   document.addEventListener('resume', function () {
    //     if (window.location.href.indexOf("hrCenter") !== -1) {
    //       //console.log("resume");
    //       t.getInfo && t.getInfo();
    //     }
    //   })
    // })
  }
  componentWillMount() {
    this.getInfo();
  }

  getInfo = async () =>{
    const getEmpCenterInfo = "/hrmregister/mobile/workbench/getEmpCenterInfo";
    const cacheData = await getCacheData(getEmpCenterInfo);
    if (cacheData) {
      this.setState({
        hrCenterInfo: cacheData
      });
    }
    this.props.actions.fetchServiceCenterInfo({ isCache: !!cacheData }).then(res => {
      let showNotification = false;
      if(res.result.generalAdmin && !res.result.alreadyInited) {
        showNotification = true;
      }
      if (res.success) {
        this.setState({
          hrCenterInfo: res.result,
          showNotification
        });
        setCacheData(getEmpCenterInfo, res.result);
      }
    });
  }

  toLink = url => {
    // console.log("toLink" + url);
    window.dd.biz.util.openLink({ url: url, enableShare: true });
  };

  link = (url, useOpenLink, needRefresh) => {

    //需要刷新页面
    if (needRefresh) window.needRefresh = needRefresh;
    // console.log("href" + url + "|useOpenLink:" + useOpenLink);

    if (useOpenLink) {
      this.toLink(url);
    } else {
      window.location.href = url;
    }
  };

  buildFlowItem(url, icon, name, useOpenLink, needRefresh) {
    return (
      <li
        className="menu-item"
        key={url}
        onClick={() => {
          this.link(url, useOpenLink,needRefresh)}
        }
      >
        <img src={icon} alt="" />
        <p>{name}</p>
      </li>
    );
  }

  buildNumberStatItem(url, number, text, useOpenLink) {
    return (
      <li
        className="menu-item"
        key={url}
        onClick={() =>{
          if(number===0){
            const titleText = encodeURI(text);
            // this.toLink(`?text=${titleText}#/noDataPage`);
            const preUrl = window.location.protocol + "//" +
                window.location.host +
                window.location.pathname +
                `?text=${titleText}#/noDataPage`;
            this.link(preUrl, useOpenLink);
            return;
          }
            this.link(url, useOpenLink)
          
          }
        }
      >
        <div> 
          <span>{number}</span>
        </div>
        <p>{text}</p>
      </li>
    );
  }

  buildItemGroup(itemGroup, title) {
    if (!itemGroup || itemGroup.length === 0) {
      return null;
    }

    const itemList = [];

    itemGroup.map((item, index) => {
      itemList.push(
        this.buildFlowItem(
          item.url,
          item.icon,
          item.name,
          item.useOpenLink,
          index % 2 === 0,
          item.needRefresh
        )
      );
    });

    return (
      <div className="employee-roster">
        <h4>{title}</h4>
        <ul>{itemList}</ul>
      </div>
    );
  }

  buildStatisticModule(hrCenterInfo) {
    if (!hrCenterInfo || !hrCenterInfo.processItemGroup) {
      return null;
    }

    return (
      <div>
        {this.buildItemGroup(
          hrCenterInfo.processItemGroup.GROUP_APPROVE_TO_EMP,
          "人事服务"
        )}
        <WhiteSpace size="lg" />

        {this.buildItemGroup(
          hrCenterInfo.processItemGroup.GROUP_ATTENDANCE,
          "我的假勤"
        )}
      </div>
    );
  }

  @autobind
  closeNotification() {
    const corpId = get("corpId");
    window.localStorage.setItem(`serviceCenter_closeNotice${corpId}`,"true");
    this.setState({
      showNotification: false
    })
  }

  @autobind
  notifyAdmin() {
    this.props.actions.inviteOpenHrmCenter().then(res => {
      if (res.success) {
        toast({ text: "已发送", icon: "success" });
        // this.setState({
        //   showNotification: false
        // })
      }      
    })
  }

  render() {
    const { hrCenterInfo } = this.state;
    const corpId = get("corpId");
    return (
      <div className="employee-manage-wrap send-manager">    
        {
          this.state.showNotification && (window.localStorage.getItem(`serviceCenter_closeNotice${corpId}`) !== "true") &&
          <div className="notification_container">
            <div className="close_btn" onClick={this.closeNotification}>
              <Icon type="close" />
            </div>
            <img src="https://gw.alicdn.com/tfs/TB18ROZbMvD8KJjy0FlXXagBFXa-957-1434.png" className="feature_img" alt="feature_img" />
            <Button className="notify_btn" type="primary" onClick={this.notifyAdmin}>
              联系主管理员开通权限
            </Button>
          </div>
        }
        {this.buildStatisticModule(hrCenterInfo)}
      </div>
    );
  }
}
